package controllers

import (
	// "encoding/json"
	"errors"
	"farmyard/models"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	share_models "share/models"
	"share/utils"
	"strings"
	"time"
)

type UserController struct {
	BaseController
}

type WxJsonResult struct {
	Openid     string `json:"openid"`
	SessionKey string `json:"session_key"`
	Unionid    string `json:"unionid"`
	Errmsg     string `json:"errmsg"`
	Errcode    int    `json:"errcode"`
}

// @Title Get
// @Description 微信登录调用code2Session
// @Param   code	 	query   string 	true "搜索内容"
// @Success 200 {object} models.User
// @Failure 403 :uid is empty
// @router /wx/login [get]
func (c *UserController) Login() {
	var result WxJsonResult
	db := c.FYDB()
	code := c.GetString("code")
	wxModel := share_models.NewWxClient()
	apiJscode2session := beego.AppConfig.String("wx_api_jscode2session")
	req := httplib.Get(wxModel.Host + apiJscode2session)
	req.Param("appid", wxModel.AppId)
	req.Param("secret", wxModel.AppSecret)
	req.Param("js_code", code)
	req.Param("grant_type", "authorization_code")
	err := req.ToJSON(&result)
	c.ErrStop(err)

	var user models.WxUser
	user.Openid = result.Openid
	fmt.Println(user.Openid)
	has, err := db.Get(&user)

	// c.Ctx.SetCookie("uid", idStr, cookieTime)
	cookieTime := 3600 * 16
	c.Ctx.SetCookie("openid", user.Openid, cookieTime)
	c.Ctx.SetCookie("accessToken", utils.Base64(strings.Join([]string{user.Openid,
		beego.AppConfig.String("accessTokenKey"), time.Now().Format("2006010215")}, "|")), cookieTime)

	c.ErrStop(err)
	if !has {
		// db.Insert(&user)
		_, err := db.Insert(user)
		c.ErrStop(err)
		fmt.Println("Insert")
	}

	c.Data["json"] = result
	c.ServeJSON()
}

// @Description 更新用户信息
// @Success 200 {status:0,Message:"success",data:{}}
// @Param   openid		formData  	string	true  "id"
// @Param   nickName 	query   	string 	false "用户名"
// @Param   city     	query   	string 	false "城市"
// @Param   gender		query   	int 	false "性别 0：未知、1：男、2：女'"
// @Param   province	query   	string 	false "省"
// @Param   country		query   	string 	false "国家"
// @Param   avatarUrl	formData   	string 	false "头像url"
// @Param   phone		formData   	string 	false "绑定手机"
// @Param   unionid		query   	string 	false "用户在微信开放平台的唯一标识符"
// @router /wx/update [post]
func (c *UserController) Update() {

	c.CheckLogin()
	var user models.WxUser
	c.ParseForm(&user)

	c.Success(user)
}

// @Title 获取用户信息
// @Description 通过id或openid获取用户信息
// @Param   openid	 	query   string 	false "微信opneid"
// @Param   uid	 		query   int32 	false "用户id"
// @Success 200 {object} models.User
// @router /wx/user [get]
func (c *UserController) Get() {
	openid := c.GetString("openid")
	uid, _ := c.GetInt32("uid")
	if uid < 1 && openid == "" {
		c.ErrStop(errors.New("need uid or openid"))
	}
	sqlparams := map[string]interface{}{
		"uid":    uid,
		"openid": openid,
	}
	db := c.FYDB()
	var user models.WxUser
	has, err := db.SqlTemplateClient("users.query.stpl", &sqlparams).Get(&user)
	c.ErrStop(err)
	if !has {
		c.ErrStop(errors.New("no result"))
	}
	c.Success(user)
}
